<!--suppress JSValidateTypes -->
<script>
/**
 * 为了方面菜单更新，菜单数据最好通过 store 更新
 *
 *    props: {
 *      collapse: boolean,
 *      items: array<menu|menus>
 *    }
 *    menus: {
 *      items: array<menu|menus>,
 *      ...el-submenu
 *    }
 */
export default {
  props: {
    /**
     * @type object[]
     * 菜单数据
     */
    items: {
      type: Array,
      default: () => []
    },
    /**
     * @type string
     * 菜单折叠时图标大小
     */
    collapseIconSize: {
      type: String,
      default: '19px'
    },
    /**
     * @type string
     * 菜单展开时的图标大小
     */
    extendIconSize: {
      type: String,
      default: '15px'
    },
    /**
     * @type string
     * 菜单展开时的文字大小
     */
    font: {
      type: String,
      default: '12px'
    },
    /**
     * @type bool
     * 是否折叠菜单
     */
    collapse: {
      type: Boolean,
      default: false
    }
  },
  functional: true,
  render (h, context) {
    // const vm = this
    /**
     * Icon绘制
     */
    const renderIcon = (h, icon = 'el-icon-menu') => {
      let fontSize = context.props.collapse ? context.props.collapseIconSize : context.props.extendIconSize
      let attrs = {
        class: icon,
        style: {
          fontSize
        }
      }
      return h('i', { ...attrs })
    }
    /**
     * 标题绘制
     */
    const renderTitle = (h, label) => {
      let fontSize = context.props.font
      let attrs = {
        style: {
          fontSize
        }
      }
      return h('span', { ...attrs, slot: 'title' }, label)
    }

    const renderContent = (h, item) => {
      let children = [renderIcon(h, item.icon)]
      if (!context.props.collapse) children.push(renderTitle(h, item.label))
      children.push()
      return children
    }

    /**
     * 绘制菜单项
     */
    const renderMenuItem = (h, item) => {
      const props = {
        ...item,
        index: item.id + ''
      }

      return h('el-menu-item', {
        props
      }, renderContent(h, item))
    }

    /**
     * 绘制菜单
     */
    const renderItems = (h, items) => {
      const renderReduce = (h, item) => {
        return h('el-submenu', {
          props: {
            ...item,
            index: item.id + ''
          }
        }, [
          h('template', { slot: 'title' }, renderContent(h, item)),
          ...renderItems(h, item.items)]
        )
      }
      return items.reduce((acc, item) => {
        if (item.items) {
          acc.push(renderReduce(h, item))
        } else {
          acc.push(renderMenuItem(h, item))
        }
        return acc
      }, [])
    }

    return h(
      'el-menu',
      context.data,
      renderItems(h, context.props.items)
    )
  }
}
</script>
